package com.aizhixin.lab.project.course.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.entity.User;
import com.aizhixin.lab.company.repository.UserRepository;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.project.course.data.GroupMemberData;
import com.aizhixin.lab.project.course.data.GroupResultData;
import com.aizhixin.lab.project.course.domain.*;
import com.aizhixin.lab.project.course.entity.*;
import com.aizhixin.lab.project.course.repository.*;
import com.aizhixin.lab.project.course.service.ProjectClassStuService;
import com.aizhixin.lab.project.course.service.ProjectPeopleEvaluatingService;
import com.aizhixin.lab.project.course.service.ProjectReplyService;
import com.aizhixin.lab.project.course.service.ReleaseProjectReplyService;
import com.aizhixin.lab.project.course.uilt.DoubleUtil;
import com.aizhixin.lab.project.course.vo.*;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RequestMapping("/api/v1/project/reply")
@RestController
@Api(value = "项目答辩", tags = "项目答辩")
public class ProjectReplyController {
    @Autowired
    private ProjectReplyService projectReplyService;
    @Autowired
    private ProjectReplyRepository projectReplyRepository;
    @Autowired
    private ProjectGroupRepository projectGroupRepository;
    @Autowired
    private ProjectClassStuService projectClassStuService;
    @Autowired
    private ProjectClassRepository projectClassRepository;
    @Autowired
    private ProjectClassStuRepository projectClassStuRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ProjectGroupScoreRepository projectGroupScoreRepository;
    @Autowired
    private ProjectReplyWeightRepository projectReplyWeightRepository;
    @Autowired
    private ProjectPeopleEvaluatingService projectPeopleEvaluatingService;
    @Autowired
    private TeacherProjectRepository teacherProjectRepository;
    @Autowired
    private ProjectClassStuRepository classStuRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProjectGroupTaskRepository groupTaskRepository;
    @Autowired
    private ProjectPeopleEvaluatingRepository projectPeopleEvaluatingRepository;
    @Autowired
    private Config config;
    @Autowired
    private ReleaseProjectReplyService releaseProjectReplyService;

    @RequestMapping(value = "/findEvaluationResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询项目下小组测评结果(简单表)", httpMethod = "GET", notes = "查询项目下小组测评结果(简单表)")
    public ResponseEntity<?> findEvaluationResult(@RequestHeader("Authorization") String token, @RequestParam String projectId,@RequestParam String releaseProjectReplyId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupResultData> evaluationResult = projectPeopleEvaluatingService.findEvaluationResult(releaseProjectReplyId,projectId, account.getId(), false);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, evaluationResult);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/projectGrade", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "项目期末成绩", httpMethod = "GET", notes = "项目期末成绩")
    public ResponseEntity<?> projectGrade(@RequestHeader("Authorization") String token, @RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupGradeDomain> groupGradeDomains = projectReplyService.exportGrade(projectId, false);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, groupGradeDomains);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/exportProjectGrade", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目期末成绩(简单表)", httpMethod = "GET", notes = "导出项目期末成绩(简单表)")
    public ResponseEntity<?> exportProjectGrade(@RequestHeader("Authorization") String token, @RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupGradeDomain> groupGradeDomains = projectReplyService.exportGrade(projectId, false);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("小组名称");
        row.createCell(1).setCellValue("学生名称");
        row.createCell(2).setCellValue("签到成绩");
        row.createCell(3).setCellValue("平时成绩");
        row.createCell(4).setCellValue("答辩成绩");
        int i = 1;
        HSSFCellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        for (GroupGradeDomain domain : groupGradeDomains) {
            if (domain.getGroupGradeDomainList().size() == 0) {
                continue;
            }
            CellRangeAddress callRangeAddress1 = new CellRangeAddress(i, i + domain.getGroupGradeDomainList().size() - 1, 0, 0);//起始行,结束行,起始列,结束列
            sheet.addMergedRegion(callRangeAddress1);
            for (StuGradeDomain stuGradeDomain : domain.getGroupGradeDomainList()) {
                HSSFRow row1 = sheet.createRow(i);
                HSSFCell cell = row1.createCell(0);
                cell.setCellValue(stuGradeDomain.getGroupName());
                cell.setCellStyle(style);
                row1.createCell(1).setCellValue(stuGradeDomain.getStuName());
                row1.createCell(2).setCellValue(stuGradeDomain.getSignGrade());
                row1.createCell(3).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                row1.createCell(4).setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
                i++;
            }
        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, groupGradeDomains);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/projectComplexGrade", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "项目期末成绩(复杂表)", httpMethod = "GET", notes = "项目期末成绩(复杂表)")
    public ResponseEntity<?> projectComplexGrade(@RequestHeader("Authorization") String token, @RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupGradeDomain> groupGradeDomains = projectReplyService.exportGrade(projectId, true);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, groupGradeDomains);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/newexportProjectComplexGrade", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目期末成绩(复杂表)", httpMethod = "GET", notes = "导出项目期末成绩(复杂表)")
    public ResponseEntity<?> newexportProjectComplexGrade(@RequestHeader("Authorization") String token, @RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupGradeDomain> groupGradeDomains = projectReplyService.exportGrade(projectId, true);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("小组名称");
        row.createCell(1).setCellValue("学生名称");
        row.createCell(2).setCellValue("签到成绩");
        row.createCell(3).setCellValue("平时成绩");
        row.createCell(4).setCellValue("任务名称");
        row.createCell(5).setCellValue("任务成绩");
        row.createCell(6).setCellValue("答辩成绩");
        int i = 1;
//        int maxColumnWidth = 10;
        //cell通用样式
        int j = 1;  //计算需要合并多少行

        List<CellRangeAddress> cellRangeAddressList = new ArrayList<>();
        HSSFCellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        for (GroupGradeDomain domain : groupGradeDomains) {
            for (StuGradeDomain stuGradeDomain : domain.getGroupGradeDomainList()) {
//                HSSFRow row1 = sheet.createRow(i);
//                HSSFCell cell = row1.createCell(1);
//                cell.setCellValue(stuGradeDomain.getGroupName());
//                cell.setCellStyle(style);
//                HSSFCell cell2 = row1.createCell(2);
//                cell2.setCellValue(stuGradeDomain.getStuName());
//                cell2.setCellStyle(style);
//                HSSFCell cell3 = row1.createCell(3);
//                cell3.setCellValue(stuGradeDomain.getSignGrade());
//                cell3.setCellStyle(style);
//                row1.createCell(4).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                StringBuilder stringBuilder = new StringBuilder();
                List<String> stringList = new ArrayList<>();
                if (stuGradeDomain.getKeyValueDomainList().size() > 0) {
                    CellRangeAddress callRangeAddress1 = new CellRangeAddress(i, i + stuGradeDomain.getKeyValueDomainList().size() - 1, 1, 1);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress1);
                    CellRangeAddress callRangeAddress2 = new CellRangeAddress(i, i + stuGradeDomain.getKeyValueDomainList().size() - 1, 2, 2);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress2);
                    CellRangeAddress callRangeAddress3 = new CellRangeAddress(i, i + stuGradeDomain.getKeyValueDomainList().size() - 1, 3, 3);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress3);
                    CellRangeAddress callRangeAddress6 = new CellRangeAddress(i, i + stuGradeDomain.getKeyValueDomainList().size() - 1, 6, 6);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress6);
                    for (KeyValueDomain keyValueDomain : stuGradeDomain.getKeyValueDomainList()) {
                        HSSFRow row2 = sheet.createRow(i);
                        //                HSSFRow row1 = sheet.createRow(i);
                        HSSFCell cell = row2.createCell(0);
                        cell.setCellValue(stuGradeDomain.getGroupName());
                        cell.setCellStyle(style);
                        HSSFCell cell2 = row2.createCell(1);
                        cell2.setCellValue(stuGradeDomain.getStuName());
                        cell2.setCellStyle(style);
                        HSSFCell cell3 = row2.createCell(2);
                        cell3.setCellValue(stuGradeDomain.getSignGrade());
                        cell3.setCellStyle(style);
                        HSSFCell cell4 = row2.createCell(3);
                        cell4.setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                        cell4.setCellStyle(style);
//                        row2.createCell(3).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                        HSSFCell cell6 = row2.createCell(6);
                        cell6.setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
                        cell6.setCellStyle(style);
//                        row2.createCell(0).setCellValue(stuGradeDomain.getGroupName());
//                        row2.createCell(1).setCellValue(stuGradeDomain.getStuName());
//                        row2.createCell(2).setCellValue(stuGradeDomain.getSignGrade());
//                        row2.createCell(3).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                        row2.createCell(4).setCellValue(keyValueDomain.getKey());
                        row2.createCell(5).setCellValue(keyValueDomain.getValue());
//                        row2.createCell(6).setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
                        i++;

//                    row1.setHeightInPoints(stuGradeDomain.getKeyValueDomainList().size()*20);
//                    stringList.add(keyValueDomain.getKey() + ":" + keyValueDomain.getValue());
//                    stringBuilder.append(keyValueDomain.getKey() + ":" + keyValueDomain.getValue() + "\r\n");
//                    if (keyValueDomain.getKey().length()>maxColumnWidth){
//                        maxColumnWidth=keyValueDomain.getKey().length();
//                    }
//
//                }
//                HSSFCell cell1 = row1.createCell(4);
//                String s = stringBuilder.toString();
//                cell1.setCellValue(s.substring(0, s.length() - 2));
//                HSSFCellStyle style1 = wb.createCellStyle();
//                style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//                style1.setWrapText(true);
//                cell1.setCellStyle(style1);
                    }
                } else {
                    HSSFRow row2 = sheet.createRow(i);
                    HSSFCell cell = row2.createCell(0);
                    cell.setCellValue(stuGradeDomain.getGroupName());
                    cell.setCellStyle(style);
                    HSSFCell cell2 = row2.createCell(1);
                    cell2.setCellValue(stuGradeDomain.getStuName());
                    cell2.setCellStyle(style);
                    HSSFCell cell3 = row2.createCell(2);
                    cell3.setCellValue(stuGradeDomain.getSignGrade());
                    cell3.setCellStyle(style);
                    HSSFCell cell4 = row2.createCell(3);
                    cell4.setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                    cell4.setCellStyle(style);
//                        row2.createCell(3).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                    HSSFCell cell6 = row2.createCell(6);
                    cell6.setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
                    cell6.setCellStyle(style);
                    i++;
                }

//                HSSFCell cell4 = row1.createCell(5);
//                cell4.setCellStyle(style);
//                cell4.setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
//                i++;
            }
            CellRangeAddress callRangeAddress6 = new CellRangeAddress(j, i - 1, 0, 0);//起始行,结束行,起始列,结束列
            sheet.addMergedRegion(callRangeAddress6);
            j = i;
        }
        sheet.autoSizeColumn(0, true);
        sheet.autoSizeColumn(1, true);
        sheet.autoSizeColumn(2, true);
        sheet.autoSizeColumn(3, true);
        sheet.autoSizeColumn(4, true);
        sheet.autoSizeColumn(5, true);
        sheet.autoSizeColumn(6, true);

        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, groupGradeDomains);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/exportProjectComplexGrade", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目期末成绩(复杂表)", httpMethod = "GET", notes = "导出项目期末成绩(复杂表)")
    public ResponseEntity<?> exportProjectComplexGrade(@RequestHeader("Authorization") String token, @RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupGradeDomain> groupGradeDomains = projectReplyService.exportGrade(projectId, true);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        HSSFRow row = sheet.createRow(0);
        row.createCell(1).setCellValue("小组名称");
        row.createCell(2).setCellValue("学生名称");
        row.createCell(3).setCellValue("签到成绩");
        row.createCell(4).setCellValue("平时成绩");
        row.createCell(5).setCellValue("答辩成绩");
        int i = 1;
        int maxColumnWidth = 10;
        //cell通用样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        for (GroupGradeDomain domain : groupGradeDomains) {
            for (StuGradeDomain stuGradeDomain : domain.getGroupGradeDomainList()) {
                HSSFRow row1 = sheet.createRow(i);
                HSSFCell cell = row1.createCell(1);
                cell.setCellValue(stuGradeDomain.getGroupName());
                cell.setCellStyle(style);
                HSSFCell cell2 = row1.createCell(2);
                cell2.setCellValue(stuGradeDomain.getStuName());
                cell2.setCellStyle(style);
                HSSFCell cell3 = row1.createCell(3);
                cell3.setCellValue(stuGradeDomain.getSignGrade());
                cell3.setCellStyle(style);
//                row1.createCell(4).setCellValue(stuGradeDomain.getTaskGrade().doubleValue());
                StringBuilder stringBuilder = new StringBuilder();
                List<String> stringList = new ArrayList<>();
                for (KeyValueDomain keyValueDomain : stuGradeDomain.getKeyValueDomainList()) {
                    row1.setHeightInPoints(stuGradeDomain.getKeyValueDomainList().size() * 20);
                    stringList.add(keyValueDomain.getKey() + ":" + keyValueDomain.getValue());
                    stringBuilder.append(keyValueDomain.getKey() + ":" + keyValueDomain.getValue() + "\r\n");
                    if (keyValueDomain.getKey().length() > maxColumnWidth) {
                        maxColumnWidth = keyValueDomain.getKey().length();
                    }

                }
                HSSFCell cell1 = row1.createCell(4);
                String s = stringBuilder.toString();
                cell1.setCellValue(s.substring(0, s.length() - 2));
                HSSFCellStyle style1 = wb.createCellStyle();
                //是否水平居中
//                    if (flag1) {
//                        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
//                    }

                style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                style1.setWrapText(true);
                cell1.setCellStyle(style1);
                HSSFCell cell4 = row1.createCell(5);
                cell4.setCellStyle(style);
                cell4.setCellValue(stuGradeDomain.getReplyGrade().doubleValue());
                i++;
            }
        }
        sheet.setColumnWidth(4, (maxColumnWidth + 3) * 512);

        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, groupGradeDomains);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        // TODO Auto-generated method stub
        HSSFCellStyle style = workbook.createCellStyle();
        //是否水平居中
        if (flag1) {
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
        }

        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
        //创建字体
        HSSFFont font = workbook.createFont();
        //是否加粗字体
        if (flag) {
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        }
        font.setFontHeightInPoints(fontsize);
        //加载字体
        style.setFont(font);
        return style;


    }

    @RequestMapping(value = "/exportEvaluationResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目下小组测评结果(简单表)", httpMethod = "GET", notes = "导出项目下小组测评结果(简单表)")
    public ResponseEntity<?> exportEvaluationResult(@RequestHeader("Authorization") String token, @RequestParam String projectId,@RequestParam String releaseProjectReplyId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupResultData> evaluationResult = projectPeopleEvaluatingService.findEvaluationResult(releaseProjectReplyId,projectId, account.getId(), false);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        for (int i = 0; i < 9; i++) {
            sheet.autoSizeColumn(i);
        }

//        sheet.autoSizeColumn(1, true);
        int i = 1;
        //行级
        int j = 1;
        HSSFCellStyle cellStyle = createCellStyle(wb, (short) 8, false, true);
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("小组名称");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("角色");
        row.createCell(3).setCellValue("团队综合评分");
        row.createCell(4).setCellValue("个人测评分数");
        row.createCell(5).setCellValue("个人综合评分");
        for (GroupResultData groupResultData : evaluationResult) {
//            HSSFRow row1 = sheet.createRow(i);
//            row1.createCell(1).setCellValue(groupResultData.getGroupName());

            CellRangeAddress callRangeAddress = new CellRangeAddress(j, j + groupResultData.getGroupMemberDataList().size() - 1, 0, 0);//起始行,结束行,起始列,结束列
            j += groupResultData.getGroupMemberDataList().size();
            sheet.addMergedRegion(callRangeAddress);

            for (GroupMemberData groupMemberData : groupResultData.getGroupMemberDataList()) {
                HSSFRow row2 = sheet.createRow(i);
                HSSFCell cell = row2.createCell(0);
                cell.setCellValue(groupResultData.getGroupName());
                cell.setCellStyle(cellStyle);
                row2.createCell(2).setCellValue(groupMemberData.getStuName());
                row2.createCell(3).setCellValue(groupMemberData.getRole());
                row2.createCell(4).setCellValue(groupMemberData.getGroupEvaluationGrade());
                row2.createCell(5).setCellValue(groupMemberData.getPersonalEvaluationGrade());
                row2.createCell(6).setCellValue(groupMemberData.getSynthesizeGrade());
                i++;
            }


        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, evaluationResult);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/exportEvaluationComplexResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目下小组测评结果(复杂表)", httpMethod = "GET", notes = "导出项目下小组测评结果(复杂表)")
    public ResponseEntity<?> exportEvaluationComplexResult(@RequestHeader("Authorization") String token, @RequestParam String projectId,@RequestParam String releaseProjectReplyId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupResultData> evaluationResult = projectPeopleEvaluatingService.findEvaluationResult(releaseProjectReplyId,projectId, account.getId(), true);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
//        sheet.autoSizeColumn(1);
//        sheet.autoSizeColumn(1, true);
        int i = 1;
        //行级
        int j = 1;
        int maxColumnWidth = 10;
        HSSFCellStyle cellStyle = createCellStyle(wb, (short) 8, false, true);
        //cell通用样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFRow row = sheet.createRow(0);
        HSSFCell titleCell = row.createCell(0);
        titleCell.setCellValue("小组名称");
        titleCell.setCellStyle(cellStyle);
        HSSFCell titleCell2 = row.createCell(1);
        titleCell2.setCellValue("学生名称");
        titleCell2.setCellStyle(cellStyle);
        HSSFCell titleCell3 = row.createCell(2);
        titleCell3.setCellValue("学生角色");
        titleCell3.setCellStyle(cellStyle);
        HSSFCell titleCell4 = row.createCell(3);
        titleCell4.setCellValue("团队综合评分");
        titleCell4.setCellStyle(cellStyle);
        HSSFCell titleCell5 = row.createCell(4);
        titleCell5.setCellValue("个人测评分数");
        titleCell5.setCellStyle(cellStyle);
        row.createCell(5).setCellValue("测评维度");
        row.createCell(6).setCellValue("测评分数");
        HSSFCell titleCell8 = row.createCell(7);
        titleCell8.setCellValue("个人最终得分");
        titleCell8.setCellStyle(cellStyle);
        for (GroupResultData groupResultData : evaluationResult) {
//            HSSFRow row1 = sheet.createRow(i);
//            row1.createCell(1).setCellValue(groupResultData.getGroupName());

//            CellRangeAddress callRangeAddress = new CellRangeAddress(j, j + groupResultData.getGroupMemberDataList().size() - 1, 0, 0);//起始行,结束行,起始列,结束列
//            j += groupResultData.getGroupMemberDataList().size();
//            sheet.addMergedRegion(callRangeAddress);

            for (GroupMemberData groupMemberData : groupResultData.getGroupMemberDataList()) {

                StringBuilder stringBuilder = new StringBuilder();
                List<String> stringList = new ArrayList<>();
                if (groupMemberData.getKeyValueDomains().size() > 0) {
                    CellRangeAddress callRangeAddress1 = new CellRangeAddress(i, i + groupMemberData.getKeyValueDomains().size() - 1, 1, 1);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress1);
                    CellRangeAddress callRangeAddress2 = new CellRangeAddress(i, i + groupMemberData.getKeyValueDomains().size() - 1, 2, 2);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress2);
                    CellRangeAddress callRangeAddress3 = new CellRangeAddress(i, i + groupMemberData.getKeyValueDomains().size() - 1, 3, 3);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress3);
                    CellRangeAddress callRangeAddress4 = new CellRangeAddress(i, i + groupMemberData.getKeyValueDomains().size() - 1, 4, 4);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress4);
                    CellRangeAddress callRangeAddress7 = new CellRangeAddress(i, i + groupMemberData.getKeyValueDomains().size() - 1, 7, 7);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(callRangeAddress7);
                    for (KeyValueDomain keyValueDomain : groupMemberData.getKeyValueDomains()) {
                        HSSFRow row2 = sheet.createRow(i);
                        HSSFCell cell = row2.createCell(0);
                        cell.setCellValue(groupResultData.getGroupName());
                        cell.setCellStyle(cellStyle);
                        HSSFCell cell2 = row2.createCell(1);
                        cell2.setCellValue(groupMemberData.getStuName());
                        cell2.setCellStyle(cellStyle);
                        HSSFCell cell3 = row2.createCell(2);
                        cell3.setCellValue(groupMemberData.getRole());
                        cell3.setCellStyle(cellStyle);
                        HSSFCell cell4 = row2.createCell(3);
                        cell4.setCellValue(groupMemberData.getGroupEvaluationGrade());
                        cell4.setCellStyle(cellStyle);
                        HSSFCell cell5 = row2.createCell(4);
                        cell5.setCellValue(groupMemberData.getPersonalEvaluationGrade());
                        cell5.setCellStyle(cellStyle);
                        row2.createCell(5).setCellValue(keyValueDomain.getKey());
                        row2.createCell(6).setCellValue(keyValueDomain.getValue());
                        HSSFCell cell8 = row2.createCell(7);
                        cell8.setCellValue(groupMemberData.getSynthesizeGrade());
                        cell8.setCellStyle(cellStyle);
//                        row2.setHeightInPoints(groupMemberData.getKeyValueDomains().size() * 20);
//                        stringList.add(keyValueDomain.getKey() + ":" + keyValueDomain.getValue());
//                        stringBuilder.append(keyValueDomain.getKey() + ":" + keyValueDomain.getValue() + "\r\n");
//                        if (keyValueDomain.getKey().length() > maxColumnWidth) {
//                            maxColumnWidth = keyValueDomain.getKey().length();
//                        }
                        i++;

                    }
                } else {
                    HSSFRow row2 = sheet.createRow(i);
                    HSSFCell cell = row2.createCell(0);
                    cell.setCellValue(groupResultData.getGroupName());
                    cell.setCellStyle(cellStyle);
                    HSSFCell cell2 = row2.createCell(1);
                    cell2.setCellValue(groupMemberData.getStuName());
                    cell2.setCellStyle(cellStyle);
                    HSSFCell cell3 = row2.createCell(2);
                    cell3.setCellValue(groupMemberData.getRole());
                    cell3.setCellStyle(cellStyle);
                    HSSFCell cell4 = row2.createCell(3);
                    cell4.setCellValue(groupMemberData.getGroupEvaluationGrade());
                    cell4.setCellStyle(cellStyle);
                    HSSFCell cell5 = row2.createCell(4);
                    cell5.setCellValue(groupMemberData.getPersonalEvaluationGrade());
                    cell5.setCellStyle(cellStyle);
                    HSSFCell cell8 = row2.createCell(7);
                    cell8.setCellValue(groupMemberData.getSynthesizeGrade());
                    cell8.setCellStyle(cellStyle);
                    i++;
                }
            }
            try {
                CellRangeAddress callRangeAddress6 = new CellRangeAddress(j, i - 1, 0, 0);//起始行,结束行,起始列,结束列
                sheet.addMergedRegion(callRangeAddress6);
                j = i;
            } catch (IllegalArgumentException e) {
                System.out.println(j + "--" + i);
            }
        }
        sheet.autoSizeColumn(0, true);
        sheet.autoSizeColumn(1, true);
        sheet.autoSizeColumn(2, true);
        sheet.autoSizeColumn(3, true);
        sheet.autoSizeColumn(4, true);
        sheet.autoSizeColumn(5, true);
        sheet.autoSizeColumn(6, true);
//        sheet.setColumnWidth(4, (maxColumnWidth + 3) * 512);
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        file.setWritable(true);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, evaluationResult);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findEvaluationComplexResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询项目下小组测评结果(复杂表)", httpMethod = "GET", notes = "查询项目下小组测评结果(复杂表)")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = GroupResultData.class),})
    public ResponseEntity<?> findEvaluationComplexResult(@RequestHeader("Authorization") String token, @RequestParam String projectId,@RequestParam String releaseProjectReplyId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<GroupResultData> evaluationResult = projectPeopleEvaluatingService.findEvaluationResult(releaseProjectReplyId,projectId, account.getId(), true);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, evaluationResult);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "答辩打分", httpMethod = "POST", notes = "答辩打分")
    public ResponseEntity<?> save(@RequestHeader("Authorization") String token, @RequestBody ProjectReplyListDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            projectReplyService.save(domain);
            result.put(ApiReturnConstants.SUCCESS, true);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/findProjectGroup", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询项目小组已有答辩打分", httpMethod = "POST", notes = "查询项目小组已有答辩打分")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroup.class),})
    public ResponseEntity<?> findProjectGroup(@RequestHeader("Authorization") String token, @RequestBody QueryProjectGroupDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ProjectGroup> projectGroupList = projectGroupRepository.findByProjectIdAndDeleteFlag(domain.getProjectId(), DataValidity.VALID.getState());
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, projectGroupList);
        Integer count = projectReplyRepository.countByReleaseProjectReplyIdAndDeleteFlag(domain.getReleaseProjectReplyId(), DataValidity.VALID.getState());
        if (count > 0) {
            result.put("isExistReply", true);
        } else {
            result.put("isExistReply", false);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findProjectPrincipal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "findProjectPrincipal", httpMethod = "GET", notes = "项目综合评分-查询项目负责人和是否超时")
    public ResponseEntity<?> findProjectPrincipal(@RequestHeader("Authorization") String token, @ApiParam(value = "项目ID") @RequestParam String projectId
            , @ApiParam(value = "小组ID") @RequestParam String groupId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        Map map = new HashMap();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        ProjectClassStu classStu = classStuRepository.findByProjectIdAndRoleAndGroupIdAndDeleteFlag(projectId, "leader", groupId, 0);
        if (classStu != null) {
            User user = userRepository.findOne(classStu.getStuId());
            map.put("userName", user.getName());
        } else {
            map.put("userName", "");
        }
        List<ProjectGroupTask> projectGroupTaskList = groupTaskRepository.findByProjectIdAndGroupIdAndDeleteFlag(projectId, groupId, 0);
        projectGroupTaskList.forEach(item -> {
            if (item.getPlanEndDate() != null) {
                if (item.getRealityEndDate() != null ? item.getRealityEndDate().compareTo(item.getPlanEndDate()) == 1 : new Date().compareTo(item.getPlanEndDate()) == -1) {
                    map.put("timeout", true);
                    return;
                } else {
                    map.put("timeout", false);
                }
            }
        });
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, map);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findTeacherGiveMark", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "findTeacherGiveMark", httpMethod = "GET", notes = "查询老师答辩打分")
    public ResponseEntity<?> findTeacherGiveMark(@RequestHeader("Authorization") String token,
                                                 @ApiParam(value = "发布答辩ID") @RequestParam String releaseProjectReplyId, @ApiParam(value = "小组ID") @RequestParam String groupId,
                                                 @ApiParam(value = "小组ID") @RequestParam String replyObjectId, @ApiParam(value = "小组ID") @RequestParam Integer replyType) {
        AccountDTO account = accountService.getUserByToken(token);

        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            List<ProjectReply> projectReplyList = projectReplyRepository.findByReleaseProjectReplyIdAndGroupIdAndCreatedByAndReplyObjectIdAndReplyTypeAndDeleteFlag(releaseProjectReplyId, groupId, account.getId(), replyObjectId, replyType, 0);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, projectReplyList);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findGroupMember", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询小组成员列表", httpMethod = "POST", notes = "查询小组成员列表")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectClassStutVo.class),})
    public ResponseEntity<?> findGroupMember(@RequestHeader("Authorization") String token, @RequestBody QueryProjectGroupMemberDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            List<ProjectClassStutVo> projectGroupList = projectClassStuService.findProjectGroupMember(domain);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, projectGroupList);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/releaseProjectReply", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "发布答辩", httpMethod = "POST", notes = "发布答辩")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectClassStutVo.class),})
    public ResponseEntity<?> findGroupMember(@RequestHeader("Authorization") String token, @RequestBody ReleaseProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        result = releaseProjectReplyService.releaseProjectReply(domain);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findReleaseProjectReply", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取项目下答辩列表", httpMethod = "GET", notes = "获取项目下答辩列表")
    public ResponseEntity<?> findReleaseProjectReply(@RequestHeader("Authorization") String token, @ApiParam(value = "项目ID") @RequestParam String projectId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        Map map = new HashMap();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ReleaseProjectReply> releaseProjectReply = releaseProjectReplyService.findReleaseProjectReply(projectId);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, releaseProjectReply);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/deleteReleaseProjectReply", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除发布答辩", httpMethod = "DELETE", notes = "删除发布答辩")
    public ResponseEntity<?> deleteReleaseProjectReply(@RequestHeader("Authorization") String token, @ApiParam(value = "发布答辩ID") @RequestParam String id) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        result = releaseProjectReplyService.deleteReleaseProjectReply(id);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findMarkMember", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询个人评分打分成员", httpMethod = "POST", notes = "查询个人评分打分成员")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroupLeaderVo.class),})
    public ResponseEntity<?> findMarkMember(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            //查询当前测评维度
            //List<ProjectPeopleEvaluating> peopleEvaluatingList = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlag(domain.getProjectId(),0);
            //查询组长打分
            List<ProjectGroupLeaderVo> projectGroupLeaderVos = projectReplyService.findMarkMemberStu(domain);
            //查询老师打分
            List<ProjectGroupLeaderVo> projectGroupLeaderVoList = projectReplyService.findMarkMemberTea(domain);
            /*projectGroupLeaderVoList.stream().forEach(tea->{
                final Double[] teaScore = {0.0};
                peopleEvaluatingList.forEach(weight->{
                    if (tea.getEvaluatingId().equals(weight.getId())) {
                        teaScore[0] =+  DoubleUtil.mul(tea.getScore(), weight.getWeight());
                        tea.setScore(teaScore[0]);
                    }
                });
            });
            projectGroupLeaderVos.stream().forEach(stu->{
                final Double[] stuScore = {0.0};
                peopleEvaluatingList.forEach(weight->{
                    stuScore[0] =+  DoubleUtil.mul(stu.getScore(), weight.getWeight());
                    if (stu.getEvaluatingId().equals(weight.getId())) {
                        stu.setScore(stuScore[0]);
                    }
                });
            });*/
            Map data = new HashMap();
            data.put("stu", projectGroupLeaderVos);
            data.put("tea", projectGroupLeaderVoList);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, data);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findTeamMarkMember", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询团队评分打分成员", httpMethod = "POST", notes = "查询团队评分打分成员")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroupLeaderVo.class),})
    public ResponseEntity<?> findTeamMarkMember(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            //查询组长打分
            List<ProjectGroupLeaderVo> projectGroupLeaderVos = projectReplyService.findMarkMemberStu(domain);
            //查询老师打分
            List<ProjectGroupLeaderVo> projectGroupLeaderVoList = projectReplyService.findMarkMemberTea(domain);
            Map data = new HashMap();
            data.put("stu", projectGroupLeaderVos);
            data.put("tea", projectGroupLeaderVoList);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, data);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findTeamSynthesizeMark", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询团队综合评分", httpMethod = "POST", notes = "查询团队综合评分")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroupLeaderVo.class),})
    public ResponseEntity<?> findTeamSynthesizeMark(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        Map map = projectReplyService.findTeamSynthesizeMark(domain);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, map);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findSynthesizeMark", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询个人综合评分", httpMethod = "POST", notes = "查询个人综合评分")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroupLeaderVo.class),})
    public ResponseEntity<?> findSynthesizeMark(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            //查询当前测评维度
            List<ProjectPeopleEvaluating> peopleEvaluating = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlagAndType(domain.getProjectId(), 0, domain.getReplyType());
            //查询老师打分
            List<ProjectAppraisalVo> projectAppraisalVoListTea = projectReplyService.findTeamSynthesizeMarkTea(domain);
            //学生打分
            List<ProjectAppraisalVo> projectAppraisalVoListStu = projectReplyService.findTeamSynthesizeMarkStu(domain);
            List<ProjectReplyWeight> projectReplyWeightsList = projectReplyWeightRepository.findAll();
            List<ProjectAppraisalVo> scoreList = new ArrayList<>();
            /*projectAppraisalVoListTea.forEach(tea -> {
                projectAppraisalVoListStu.forEach(stu -> {
                    peopleEvaluating.forEach(weight->{
                    if (tea.getId().equals(stu.getId())) {
                        if (weight.getId().equals(tea.getId())){
                            ProjectAppraisalVo projectAppraisalVo = new ProjectAppraisalVo();
                            projectAppraisalVo.setScore(DoubleUtil.mul(DoubleUtil.add(tea.getScore(), stu.getScore()),weight.getWeight()));
                            projectAppraisalVo.setName(stu.getName());
                            projectAppraisalVo.setId(stu.getId());
                            scoreList.add(projectAppraisalVo);
                        }
                    }
                    });
                });
            });*/

            scoreList.addAll(projectAppraisalVoListTea);
            scoreList.addAll(projectAppraisalVoListStu);
        /*projectAppraisalVoListTea.forEach(tea->{
            projectAppraisalVoListStu.forEach(stu -> {
                    if (tea.getId().equals(stu.getId())){
                        ProjectAppraisalVo projectAppraisalVo = new ProjectAppraisalVo();
                        projectAppraisalVo.setScore(DoubleUtil.add(stu.getScore(),tea.getScore()));
                        projectAppraisalVo.setName(stu.getName());
                        scoreList.add(projectAppraisalVo);
                    }
            });
        });*/
            List list = new ArrayList();
            Map<String, List<ProjectAppraisalVo>> scoreMap = scoreList.stream().collect(Collectors.groupingBy(ProjectAppraisalVo::getName));
            Map<String, List<ProjectAppraisalVo>> userNameMap = scoreList.stream().collect(Collectors.groupingBy(ProjectAppraisalVo::getUserName));
            for (String key : scoreMap.keySet()) {
                List<ProjectAppraisalVo> value = scoreMap.get(key);
                Double score = value.stream().mapToDouble(ProjectAppraisalVo::getScore).sum();
                Map map = new HashMap();
                map.put("name", key);
                map.put("score", score);
                list.add(map);
            }

            double avgScore = scoreList.size() == 0 ? 0 : scoreList.stream().mapToDouble(ProjectAppraisalVo::getScore).sum();
            ProjectGroupScore projectGroupScore = projectGroupScoreRepository.findByReleaseProjectReplyIdAndGroupId(domain.getReleaseProjectReplyId(), domain.getGroupId());
            Double stuScore = 0.0;
            Double teamScore = 0.0;
            for (ProjectReplyWeight data : projectReplyWeightsList) {
                if (data.getWeightType() == 3) {
                    stuScore = DoubleUtil.mul(avgScore, data.getWeightRatio());
                } else if (data.getWeightType() == 4) {
                    teamScore = DoubleUtil.mul(projectGroupScore == null ? 0 : projectGroupScore.getScore(), data.getWeightRatio());
                }
            }
            Map map = new HashMap();
            map.put("avgScore", avgScore / userNameMap.size());
            map.put("ultimatelyScore", DoubleUtil.add(stuScore, teamScore));
            map.put("appraisaScore", list);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, map);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/finMmemberScoreList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询成员评测列表", httpMethod = "GET", notes = "查询成员评测列表")
    public ResponseEntity<?> finMmemberScoreList(@RequestHeader("Authorization") String token, @ApiParam(value = "项目ID", required = false) @RequestParam String projectId,
                                                 @ApiParam(value = "小组ID", required = false) @RequestParam String groupId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            //查询当前测评维度
            List<ProjectPeopleEvaluating> peopleEvaluating = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlag(projectId, 0);
            List<ProjectClassStu> projectClassStuList = projectClassStuRepository.findByProjectIdAndGroupIdAndDeleteFlag(projectId, groupId, 0);
            projectClassStuList.forEach(item -> {
                QueryProjectReplyDomain domain = new QueryProjectReplyDomain();
                domain.setProjectId(projectId);
                domain.setReplyType(2);
                domain.setGroupId(groupId);
                domain.setStuId(item.getStuId());
                //查询老师打分
                List<ProjectAppraisalVo> projectAppraisalVoListTea = projectReplyService.findTeamSynthesizeMarkTea(domain);
                //学生打分
                List<ProjectAppraisalVo> projectAppraisalVoListStu = projectReplyService.findTeamSynthesizeMarkStu(domain);
                List<ProjectReplyWeight> projectReplyWeightsList = projectReplyWeightRepository.findAll();
                List<ProjectAppraisalVo> scoreList = new ArrayList<>();
                projectAppraisalVoListTea.forEach(tea -> {
                    projectAppraisalVoListStu.forEach(stu -> {
                        peopleEvaluating.forEach(weight -> {
                            if (tea.getId().equals(stu.getId())) {
                                if (weight.getId().equals(tea.getId())) {
                                    ProjectAppraisalVo projectAppraisalVo = new ProjectAppraisalVo();
                                    projectAppraisalVo.setScore(DoubleUtil.mul(DoubleUtil.add(tea.getScore(), stu.getScore()), weight.getWeight()));
                                    projectAppraisalVo.setName(stu.getName());
                                    projectAppraisalVo.setId(stu.getId());
                                    projectAppraisalVo.setUserId(stu.getUserId());
                                    projectAppraisalVo.setUserName(stu.getUserName());
                                    if (stu.getRole().equals("member")) {
                                        projectAppraisalVo.setRole("成员");
                                    } else if (stu.getRole().equals("leader")) {
                                        projectAppraisalVo.setRole("组长");
                                    }
                                    scoreList.add(projectAppraisalVo);
                                }

                            }
                        });
                    });
                });

                double avgScore = scoreList.size() == 0 ? 0 : scoreList.stream().mapToDouble(ProjectAppraisalVo::getScore).sum();
                ProjectGroupScore projectGroupScore = projectGroupScoreRepository.findByReleaseProjectReplyIdAndGroupId(domain.getReleaseProjectReplyId(), domain.getGroupId());
                Double stuScore = 0.0;
                Double teamScore = 0.0;
                for (ProjectReplyWeight data : projectReplyWeightsList) {
                    if (data.getWeightType() == 3) {
                        stuScore = DoubleUtil.mul(avgScore, data.getWeightRatio());
                    } else if (data.getWeightType() == 4) {
                        teamScore = DoubleUtil.mul(projectGroupScore == null ? 0 : projectGroupScore.getScore(), data.getWeightRatio());
                    }
                }
               /* Map map = new HashMap();
                map.put("avgScore", avgScore);
                map.put("ultimatelyScore", DoubleUtil.add(stuScore, teamScore));
                map.put("appraisaScore", scoreList);*/
                for (ProjectAppraisalVo data : scoreList) {
                    data.setScore(DoubleUtil.add(stuScore, teamScore));
                }
                result.put(ApiReturnConstants.SUCCESS, true);
                result.put(ApiReturnConstants.DATA, scoreList);
            });
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/findMemberEvaluating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询成员个人评测", httpMethod = "POST", notes = "查询成员个人评测")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectGroupLeaderVo.class),})
    public ResponseEntity<?> findMemberEvaluating(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        List<Map> restLisst = new ArrayList<>();
        //查询当前测评维度
        List<ProjectPeopleEvaluating> peopleEvaluatingList = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlagAndType(domain.getProjectId(), 0, 1);
        //查询组长打分
        //List<ProjectMemberEvaluatingVo> projectGroupLeaderVos = projectReplyService.findMemberEvaluating(domain);
        //组长打分*占比以后的数据
        List<ProjectMemberEvaluatingVo> projectGroupLeaderVosRiteStu = projectReplyService.findMemberEvaluatingRiteStu(domain);
        //老师打分*占比以后的数据
        List<ProjectMemberEvaluatingVo> projectGroupLeaderVosRiteTea = projectReplyService.findMemberEvaluatingRiteTea(domain);
            /*if (projectGroupLeaderVosRiteStu.size() > 0) {
                projectGroupLeaderVosRiteStu.forEach(stu -> {
                    projectGroupLeaderVosRiteTea.forEach(tea -> {
                        peopleEvaluatingList.forEach(weight -> {
                            if (stu.getCode().equals(tea.getCode()) && stu.getUserName().equals(tea.getUserName()) && weight.getId().equals(tea.getId())) {
                                stu.setScore(DoubleUtil.mul(DoubleUtil.add(stu.getScore(), tea.getScore()), weight.getWeight()));
                            }
                        });
                    });
                });
            }else {
                projectGroupLeaderVosRiteTea.forEach(tea -> {
                    peopleEvaluatingList.forEach(weight -> {
                        if (weight.getId().equals(tea.getId())) {
                            tea.setScore(DoubleUtil.mul(tea.getScore(), weight.getWeight()));
                        }
                    });
                });
            }*/
        Set<ProjectMemberEvaluatingVo> hashSet = new HashSet<ProjectMemberEvaluatingVo>();
        hashSet.addAll(projectGroupLeaderVosRiteTea);
        hashSet.addAll(projectGroupLeaderVosRiteStu);
        List<Long> longList = new ArrayList<>();
        List<Long> stuList = projectGroupLeaderVosRiteStu.stream().map(ProjectMemberEvaluatingVo::getUserId).collect(Collectors.toList());
        List<Long> teaList = projectGroupLeaderVosRiteTea.stream().map(ProjectMemberEvaluatingVo::getUserId).collect(Collectors.toList());
        List<Long> stuUserIds = stuList.stream().distinct().filter(t -> !teaList.contains(t)).collect(Collectors.toList());
        List<Long> teaUserIds = teaList.stream().distinct().filter(t -> !stuList.contains(t)).collect(Collectors.toList());
        longList.addAll(teaUserIds);
        longList.addAll(stuUserIds);

        List<ProjectMemberEvaluatingVo> projectMemberEvaluatingVoStuList = new ArrayList<>();
        List<ProjectMemberEvaluatingVo> projectMemberEvaluatingVoTeaList = new ArrayList<>();
        List<ProjectMemberEvaluatingVo> projectMemberEvaluatingVoList = new ArrayList<>();
        List<ProjectMemberEvaluatingVo> pList = new ArrayList<>();

        if (projectGroupLeaderVosRiteTea.size() > projectGroupLeaderVosRiteStu.size()) {
            AtomicInteger teaInt = new AtomicInteger();
            AtomicInteger stuInt = new AtomicInteger();
            projectGroupLeaderVosRiteTea.forEach(tea -> {
                projectGroupLeaderVosRiteStu.forEach(stu -> {
                    if (stu.getId().equals(tea.getId()) && stu.getUserId().equals(tea.getUserId())) {
                        tea.setScore(DoubleUtil.add(tea.getScore(), stu.getScore()));
                        projectMemberEvaluatingVoTeaList.add(tea);
                    }
                    if (longList.contains(stu.getUserId()) && stuInt.get() < peopleEvaluatingList.size()) {
                        projectMemberEvaluatingVoTeaList.add(stu);
                        stuInt.getAndIncrement();
                    }
                });
                if (longList.contains(tea.getUserId()) && teaInt.get() < peopleEvaluatingList.size()) {
                    projectMemberEvaluatingVoTeaList.add(tea);
                    teaInt.getAndIncrement();
                }
            });
        } else {
            AtomicInteger stuInt = new AtomicInteger();
            AtomicInteger teaInt = new AtomicInteger();
            projectGroupLeaderVosRiteStu.forEach(stu -> {
                projectGroupLeaderVosRiteTea.forEach(tea -> {
                    if (stu.getId().equals(tea.getId()) && stu.getUserId().equals(tea.getUserId())) {
                        stu.setScore(DoubleUtil.add(tea.getScore(), stu.getScore()));
                        projectMemberEvaluatingVoStuList.add(stu);
                    }
                    if (longList.contains(tea.getUserId()) && teaInt.get() < peopleEvaluatingList.size()) {
                        projectMemberEvaluatingVoStuList.add(tea);
                        teaInt.getAndIncrement();
                    }
                });
                if (longList.contains(stu.getUserId()) && stuInt.get() < peopleEvaluatingList.size()) {
                    projectMemberEvaluatingVoStuList.add(stu);
                    stuInt.getAndIncrement();
                }
            });
        }

        projectMemberEvaluatingVoList.addAll(projectMemberEvaluatingVoTeaList);
        projectMemberEvaluatingVoList.addAll(projectMemberEvaluatingVoStuList);
        Map<String, List<ProjectMemberEvaluatingVo>> listMap = projectMemberEvaluatingVoList.stream().collect(Collectors.groupingBy(ProjectMemberEvaluatingVo::getUserName));
        //表头查询
        List<ProjectEvaluatingaTableDomain> peopleEvaluating = projectPeopleEvaluatingService.findEvaluatingTableHade(domain);
        List<ProjectReplyWeight> projectReplyWeightsList = projectReplyWeightRepository.findAll();
        ProjectGroupScore projectGroupScore = projectGroupScoreRepository.findByReleaseProjectReplyIdAndGroupId(domain.getReleaseProjectReplyId(), domain.getGroupId());
        for (Map.Entry<String, List<ProjectMemberEvaluatingVo>> entry : listMap.entrySet()) {
            Map map = new HashMap();
            List<ProjectMemberEvaluatingVo> mapValue = entry.getValue();
            for (ProjectMemberEvaluatingVo data : mapValue) {
                for (ProjectEvaluatingaTableDomain tableDomain : peopleEvaluating) {
                    if (data.getCode().equals(tableDomain.getId())) {
                        map.put("userName", data.getUserName());
                        if (data.getRole().equals("member")) {
                            map.put("roleName", "成员");
                        } else if (data.getRole().equals("leader")) {
                            map.put("roleName", "组长");
                        }
                        double avgScore = mapValue.stream().mapToDouble(ProjectMemberEvaluatingVo::getScore).sum();
                        Double stuScore = 0.0;
                        Double teamScore = 0.0;
                        for (ProjectReplyWeight dataWeight : projectReplyWeightsList) {
                            if (dataWeight.getWeightType() == 3) {
                                stuScore = DoubleUtil.mul(avgScore, dataWeight.getWeightRatio());
                            } else if (dataWeight.getWeightType() == 4) {
                                teamScore = DoubleUtil.mul(projectGroupScore.getScore(), dataWeight.getWeightRatio());
                            }
                        }
                        map.put(data.getCode(), data.getScore());
                        map.put("userId", data.getUserId());
                        map.put("userName", data.getUserName());
                        map.put("synthesizeScore", avgScore);
                        map.put("ultimateScore", DoubleUtil.add(stuScore, teamScore));
                    }
                }
            }
            restLisst.add(map);
        }

        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, restLisst);

        return new ResponseEntity(result, HttpStatus.OK);
    }


}
